package cn.openea.perpartner.payment.rabbit.service.impl;


import cn.openea.perpartner.common.core.manager.AsyncManager;
import cn.openea.perpartner.payment.rabbit.domain.BusinessDto;
import cn.openea.perpartner.payment.rabbit.factory.BusinessServiceFactory;
import cn.openea.perpartner.payment.rabbit.service.BusinessService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Weird077
 * @description TODO
 * @date 2023-02-07 16:35
 */
@Slf4j
@Component
public class ConsumerService {
    /**
     * 消费业务队列
     * @param object
     * @param deliveryTag
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = "${rabbit.business.queue}",containerFactory = "batchQueueRabbitListenerContainerFactory")
    public void receiveBusiness(JSONObject object, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws IOException {
        BusinessDto businessDto = JSON.toJavaObject(object, BusinessDto.class);
        try {
            //1、通过beanName获取对应的延时处理类
            BusinessService businessService = BusinessServiceFactory.getHandler(businessDto.getBeanName());
            //2、执行延时处理类的业务逻辑
            AsyncManager.me().execute(businessService.execute(businessDto));
            //3、消息消费成功，手动确认消息,消息从队列中删除
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error(e.getMessage());
            //消息消费失败，手动拒绝消息,消息从队列中删除
            channel.basicNack(deliveryTag, false, false);
        }
    }
}
